package com.ledim.datastatistics;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import com.letv.datastatistics.util.DEs;
import com.letv.tracker2.enums.NetworkModel;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.regex.Pattern;

public final class AnalysisDataUtils {

    private AnalysisDataUtils() {
    }

    public static String getData(String data) {
        if (data == null || data.length() <= 0) {
            return "-";
        } else {
            return removeQuote(data.replace(" ", "_"));
        }
    }

    public static String getTrimData(String data) {
        return TextUtils.isEmpty(data) ? "-" : data.trim();
    }

    public static String getDataEmpty(String data) {
        if (data == null || data.length() <= 0) {
            return "";
        } else {
            return data.replace(" ", "_");
        }
    }

    public static String getData(long data) {
        return data <= 0 ? "-" : String.valueOf(data);
    }

    /**
     * 当字符串含有引号时，去除
     *
     * @return
     */
    public static String removeQuote(String data) {
        if (!TextUtils.isEmpty(data) && data.contains("\"")) {
            data = data.replace("\"", "");
        }
        return data;
    }

    public static NetworkInfo getAvailableNetWorkInfo(Context context) {

        if (context == null) {
            return null;
        }

        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
        if (activeNetInfo != null && activeNetInfo.isAvailable()) {
            return activeNetInfo;
        } else {
            return null;
        }
    }

    /**
     * 返回联网类型
     *
     * @param context
     * @return wifi或3G
     */
    public static String getNetType(Context context) {
        String type = "network";
        if (context != null) {
            try {
                ConnectivityManager connectivityManager =
                        (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isAvailable()) {
                    if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
                        type = "wifi";
                    } else {
                        TelephonyManager telephonyManager =
                                (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
                        switch (telephonyManager.getNetworkType()) {
                            case TelephonyManager.NETWORK_TYPE_GPRS:
                            case TelephonyManager.NETWORK_TYPE_CDMA:
                            case TelephonyManager.NETWORK_TYPE_EDGE:
                                type = "2g";
                                break;
                            case TelephonyManager.NETWORK_TYPE_LTE:
                                type = "4g";
                                break;
                            default:
                                type = "3g";
                                break;
                        }
                    }
                } else {
                    type = "nont";
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        return type;
    }

    /**
     * 获得ip地址
     */
    public static String getLocalIpAddress() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
                 en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses();
                     enumIpAddr.hasMoreElements(); ) {
                    InetAddress inetAddress = enumIpAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {

        }
        return "";
    }

    public static String generateDeviceId(Context context) {
        String devicesID = getIMEI(context) + getIMSI(context) + getDeviceName() + getBrandName() +
                getMacAddress(context);
        devicesID = MD5Helper(devicesID);
        return devicesID;
    }

    private static String generate_DeviceId(Context context) {
        String str = getIMEI(context) + getDeviceName() + getBrandName() + getMacAddress(context);
        return MD5Helper(str);
    }

    public static String getUUID(Context context) {
        return generateDeviceId(context) + "_" + System.currentTimeMillis();
    }

    public static String MD5Helper(String str) {
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            messageDigest.reset();
            messageDigest.update(str.getBytes("UTF-8"));
            byte[] byteArray = messageDigest.digest();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < byteArray.length; i++) {
                if (Integer.toHexString(0xFF & byteArray[i]).length() == 1) {
                    sb.append("0").append(Integer.toHexString(0xFF & byteArray[i]));
                } else {
                    sb.append(Integer.toHexString(0xFF & byteArray[i]));
                }
            }
            return sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        throw new RuntimeException("no device Id");
    }

    /**
     * 获取IMEI
     *
     * @param context
     * @return
     */
    public static String getIMEI(Context context) {
        String deviceId = "";
        if (context == null) {
            return deviceId;
        }
        try {
            deviceId =
                    ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId();
            deviceId = TextUtils.isEmpty(deviceId) ? "" : deviceId.replace(" ", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return deviceId;
    }

    /**
     * 获取加密后的IMEI
     *
     * @param context
     * @param key
     * @return
     */
    //public static String getEncryptIMEI(Context context, String key) {
    //    String imei = getIMEI(context);
    //    return TextUtils.isEmpty(imei) ? "-" : DEs.encode(key, imei.getBytes());
    //}

    /**
     * 获取加密后的IMSI
     *
     * @param context
     * @param key
     * @return
     */
    public static String getEncryptIMSI(Context context, String key) {
        String subscriberId = "-";
        try {
            if (context != null) {
                subscriberId =
                        ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
                return TextUtils.isEmpty(subscriberId) ? "-"
                                                       : DEs.encode(key, subscriberId.getBytes());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return subscriberId;
    }

    public static String getIMSI(Context context) {
        if (context == null) {
            return "";
        }
        String subscriberId = null;
        try {
            subscriberId =
                    ((TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE)).getSubscriberId();
            if (null == subscriberId || subscriberId.length() <= 0) {
                subscriberId = generate_DeviceId(context);
            } else {
                subscriberId.replace(" ", "");
                if (TextUtils.isEmpty(subscriberId)) {
                    subscriberId = generate_DeviceId(context);
                }
            }
            return subscriberId;
        } catch (Exception e) {
            e.printStackTrace();
            return subscriberId;
        }
    }

    public static String getResolution(Context context) {
        if (context == null) {
            return "";
        }
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return new StringBuilder().append(dm.widthPixels)
                                  .append("*")
                                  .append(dm.heightPixels)
                                  .toString();
    }

    public static String getNewResolution(Context context) {
        if (context == null) {
            return "";
        }
        try {
            DisplayMetrics dm = context.getResources().getDisplayMetrics();
            return new StringBuilder().append(dm.widthPixels)
                                      .append("_")
                                      .append(dm.heightPixels)
                                      .toString();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return null;
    }

    public static String getDensity(Context context) {
        if (context == null) {
            return "";
        }
        DisplayMetrics dm = context.getResources().getDisplayMetrics();
        return String.valueOf(dm.density);
    }

    /**
     * 得到设备名字
     */
    public static String getDeviceName() {
        String model = android.os.Build.MODEL;
        if (model == null || model.length() <= 0) {
            return "";
        } else {
            return model;
        }
    }

    /**
     * 得到品牌名字
     */
    public static String getBrandName() {
        String brand = android.os.Build.BRAND;
        if (brand == null || brand.length() <= 0) {
            return "";
        } else {
            return brand;
        }
    }

    /**
     * 得到客户端版本信息
     *
     * @param context
     * @return
     */
    public static String getClientVersionName(Context context) {
        if (context == null) {
            return "";
        }
        try {
            PackageInfo packInfo =
                    context.getPackageManager().getPackageInfo(context.getPackageName(), 0);
            return packInfo.versionName;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 得到设备名字
     */
    public static String getSystemName() {
        return "android";
    }

    /**
     * 得到操作系统版本号
     */
    public static String getOSVersionName() {
        return android.os.Build.VERSION.RELEASE;
    }

    /**
     * 获得行为统计扩展信息
     *
     * @param params
     * @return
     */
    public static String getExtraStr(String... params) {
        String retStr = null;
        StringBuilder sb = new StringBuilder();
        for (String s : params) {
            sb.append(s).append(";");
        }

        retStr = sb.toString();
        if (retStr.length() > 1) {
            retStr = retStr.substring(0, retStr.length() - 1);
        }

        return retStr;
    }

    /**
     * 获得行为统计扩展信息
     *
     * @param list
     * @return
     */
    public static String getExtraStr(List<String> list) {
        final int size = list.size();
        String[] params = list.toArray(new String[size]);
        return getExtraStr(params);
    }

    /**
     * 获得pid_vid
     *
     * @param pid
     * @param vid
     * @return
     */
    public static String getIds(String pid, String vid) {
        StringBuilder builder = new StringBuilder();
        builder.append(TextUtils.isEmpty(pid) ? "-" : pid);
        builder.append("_");
        builder.append(TextUtils.isEmpty(vid) ? "-" : vid);
        return builder.toString();
    }

    /**
     * 获取错误码字符串,特殊用
     */
    public static String getErrorMessage(String pcode, String did, String version,
                                         String actionId) {
        StringBuilder sb = new StringBuilder();
        sb.append(did)
          .append("_")
          .append(System.currentTimeMillis())
          .append("_")
          .append(version)
          .append("_")
          .append(actionId)
          .append("_")
          .append(pcode);
        return sb.toString();
    }

    /**
     * 返回指定格式的时间
     *
     * @return
     */
    public static String timeClockString(String format) {
        // 按自定义格式SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        SimpleDateFormat formatTime = new SimpleDateFormat(format);
        Date currentTime = new Date();
        return formatTime.format(currentTime);
    }

    /**
     * 获取cpu内核频率(单位：MHZ)
     *
     * @param type
     *         1:最大主频 2：最小主频 其它：当前主频
     * @return
     */
    public static int getCpuFrequency(int type) {
        String path = "/sys/devices/system/cpu/cpu0/cpufreq/";
        if (type == 1) { //最大主频
            path += "cpuinfo_max_freq";
        } else if (type == 2) { // 最小主频
            path += "cpuinfo_min_freq";
        } else { //当前主频
            path += "scaling_cur_freq";
        }

        int result = 0;
        BufferedReader br = null;
        try {
            FileReader fr = new FileReader(path);
            br = new BufferedReader(fr);
            String text = br.readLine();
            result = Integer.parseInt(text.trim()) / 1000;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                }
            }
        }
        return result;
    }

    /**
     * 获取当前连接的wifi名称
     *
     * @return
     */
    public static String getConnectWifiSsid(Context context) {
        if (context == null) {
            return "";
        }
        String ssid = "";
        try {
            WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            WifiInfo wifiInfo = wifiManager.getConnectionInfo();
            ssid = wifiInfo.getSSID();
        } catch (Exception e) {
        }
        return ssid;
    }

    /**
     * 获取本机MAC地址
     *
     * @param context
     * @return
     */
    public static String getMacAddress(Context context) {
        if (context == null) {
            return "";
        }
        try {
            String macAddress = null;
            WifiInfo wifiInfo =
                    ((WifiManager) context.getSystemService(Context.WIFI_SERVICE)).getConnectionInfo();
            macAddress = wifiInfo.getMacAddress();
            if (macAddress == null || macAddress.length() <= 0) {
                return "";
            } else {
                return macAddress;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 取得去掉冒号的mac地址
     *
     * @return
     */
    public static String getNoColonMacAddress(Context context) {
        String macAddress = getMacAddress(context);
        return TextUtils.isEmpty(macAddress) ? "" : macAddress.replace(":", "");
    }

    /**
     * 获取本机wifi下的ip地址
     *
     * @param context
     * @return
     */
    public static String getWifiMacAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifiManager.getConnectionInfo();
        String ipString = "-";// 本机在WIFI状态下路由分配给的IP地址
        if (info != null) {
            int ipAddress = info.getIpAddress();
            if (ipAddress > 0) {
                ipString = ((ipAddress & 0xff) + "." + (ipAddress >> 8 & 0xff) + "." +
                        (ipAddress >> 16 & 0xff) + "." + (ipAddress >> 24 & 0xff));
            }
        }
        return ipString;
    }

    /**
     * 取得非空数据
     *
     * @param data
     * @return
     */
    public static String getUnEmptyData(String data) {
        return TextUtils.isEmpty(data) ? "-" : data;
    }

    /**
     * Gets the number of cores available in this device, across all processors.
     * Requires: Ability to peruse the filesystem at "/sys/devices/system/cpu"
     *
     * @return The number of cores, or 1 if failed to get result
     */
    public static int getCpuNumCores() {
        //Private Class to display only CPU devices in the directory listing
        class CpuFilter implements FileFilter {

            @Override
            public boolean accept(File pathname) {
                //Check if filename is "cpu", followed by a single digit number
                return Pattern.matches("cpu[0-9]", pathname.getName());
            }
        }

        try {
            //Get directory containing CPU info
            File dir = new File("/sys/devices/system/cpu/");
            //Filter to only list the devices we care about
            File[] files = dir.listFiles(new CpuFilter());
            return files.length;
        } catch (Exception e) {
            e.printStackTrace();
            //Default to return 1 core
            return 1;
        }
    }

    /**
     * 获取手机总内存（单位：MB）
     *
     * @return
     */
    public static long getMemoryTotalSize() {
        long mTotal = 0;
        // /proc/meminfo读出的内核信息进行解释
        String path = "/proc/meminfo";
        String content = null;
        BufferedReader br = null;
        try {
            br = new BufferedReader(new FileReader(path), 8);
            String line;
            if ((line = br.readLine()) != null) {
                content = line;
            }
            if (!TextUtils.isEmpty(content)) {
                // beginIndex
                int begin = content.indexOf(':');
                // endIndex
                int end = content.indexOf('k');
                // 截取字符串信息
                content = content.substring(begin + 1, end).trim();
                mTotal = Integer.parseInt(content) / 1024;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return mTotal;
    }

    /**
     * 将uuid存储到本地
     *
     * @param context
     * @param uuid
     */
    public static void setUuidToLocal(Context context, String uuid) {
        SharedPreferences sp =
                context.getSharedPreferences("statistics", Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("uuid", uuid);
        editor.commit();
    }

    /**
     * 从本地去uuid
     *
     * @param context
     * @return
     */
    public static String getLocalUuid(Context context) {
        SharedPreferences sp =
                context.getSharedPreferences("statistics", Context.MODE_MULTI_PROCESS);
        return sp.getString("uuid", "");
    }

    /**
     * 获取aliyun os的uuid
     *
     * @return
     */
    public static String getCloudUUID() {
        // 先获取通用版本的uuid
        String uuid = getSystemProperty("ro.aliyun.clouduuid");
        if (TextUtils.isEmpty(uuid)) { //魅族版YunOS系统
            uuid = getSystemProperty("ro.sys.aliyun.clouduuid");
        }
        return uuid;
    }

    private static String getSystemProperty(String key) {
        try {
            Class<?> SystemProperties = Class.forName("android.os.SystemProperties");
            Method m = SystemProperties.getMethod("get", String.class, String.class);
            String result = (String) m.invoke(null, key, "");
            return result;
        } catch (Exception e) {
        }
        return "";
    }

    public static NetworkModel getNetworkType(Context context) {
        NetworkModel networkModel = null;
        ConnectivityManager connectivityManager =
                (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.isAvailable()) {
            if (ConnectivityManager.TYPE_WIFI == networkInfo.getType()) {
                networkModel = NetworkModel.Wifi;
            } else {
                TelephonyManager telephonyManager =
                        (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

                switch (telephonyManager.getNetworkType()) {
                    case TelephonyManager.NETWORK_TYPE_GPRS:
                    case TelephonyManager.NETWORK_TYPE_CDMA:
                    case TelephonyManager.NETWORK_TYPE_EDGE:
                        networkModel = NetworkModel._2G;
                        break;
                    case TelephonyManager.NETWORK_TYPE_LTE:
                        networkModel = NetworkModel._3G; // 4G作为3G处理
                        break;
                    default:
                        networkModel = NetworkModel._3G;
                }
            }
        }
        return networkModel;
    }

    /**
     * 播放缓冲统计 时间格式化xx.xx（单位秒）
     *
     * @param time
     */
    public static String timeToString(long time) {
        if (time > 575990000) {
            time = System.currentTimeMillis() - time;
        }
        return String.valueOf((time / 10) * 1.0f / 100);
    }
}
